package models.ru.paralainer.chat.server.util;

import models.ru.paralainer.chat.server.domain.User;
import models.ru.paralainer.chat.server.dto.UserDTO;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created By: Sergey Talov (serg.talov@gmail.com)
 * Date: 09.08.12
 * Time: 11:34
 */
public class OnlineUserHolder {

    private ConcurrentHashMap<UserDTO, Long> users = new ConcurrentHashMap<UserDTO, Long>();

    public static final Long PERIOD = 1000 * 3L; //15 seconds

    public static final OnlineUserHolder INSTANCE = new OnlineUserHolder();

    private OnlineUserHolder() {
    }

    public void addUser(User user) {
        users.put(new UserDTO(user), new Date().getTime());
    }

    public void refreshUsers() {
        for (Iterator<Map.Entry<UserDTO, Long>> iterator = users.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<UserDTO, Long> entry = iterator.next();
            if (new Date().getTime() - entry.getValue() > PERIOD) {
                iterator.remove();
            }
        }
    }

    public List<UserDTO> getUserList() {
        return new ArrayList<UserDTO>(users.keySet());
    }


}
